'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { BarChart3, TrendingUp, Calendar, Target, Award, Clock, BookOpen, Zap } from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'


interface LearningStats {
  totalStudyTime: number
  questionsAnswered: number
  correctAnswers: number
  accuracy: number
  streak: number
  topicsCompleted: number
  averageDifficulty: number
  recentActivity: number
}

interface TopicProgress {
  topicId: string
  topicName: string
  category: string
  difficulty: number
  questionsAnswered: number
  correctAnswers: number
  accuracy: number
  timeSpent: number
  lastStudied: string
}

interface DailyActivity {
  date: string
  questionsAnswered: number
  timeSpent: number
  accuracy: number
}

interface Achievement {
  id: string
  title: string
  description: string
  icon: string
  unlockedAt: string
  category: string
}

export default function AnalyticsPage() {
  const [stats, setStats] = useState<LearningStats | null>(null)
  const [topicProgress, setTopicProgress] = useState<TopicProgress[]>([])
  const [dailyActivity, setDailyActivity] = useState<DailyActivity[]>([])
  const [achievements, setAchievements] = useState<Achievement[]>([])
  const [selectedPeriod, setSelectedPeriod] = useState<'week' | 'month' | 'year'>('week')
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')

  // 模拟数据
  const mockStats: LearningStats = {
    totalStudyTime: 1250, // 分钟
    questionsAnswered: 342,
    correctAnswers: 289,
    accuracy: 84.5,
    streak: 12,
    topicsCompleted: 18,
    averageDifficulty: 2.8,
    recentActivity: 7
  }

  const mockTopicProgress: TopicProgress[] = [
    {
      topicId: 'basic-addition',
      topicName: '基础加法',
      category: '小学数学',
      difficulty: 1,
      questionsAnswered: 25,
      correctAnswers: 23,
      accuracy: 92,
      timeSpent: 45,
      lastStudied: '2025-09-24T10:30:00Z'
    },
    {
      topicId: 'rectangle-perimeter',
      topicName: '长方形周长',
      category: '几何基础',
      difficulty: 2,
      questionsAnswered: 18,
      correctAnswers: 15,
      accuracy: 83.3,
      timeSpent: 32,
      lastStudied: '2025-09-23T14:20:00Z'
    },
    {
      topicId: 'chicken-rabbit-cage',
      topicName: '鸡兔同笼',
      category: '应用题',
      difficulty: 4,
      questionsAnswered: 12,
      correctAnswers: 8,
      accuracy: 66.7,
      timeSpent: 58,
      lastStudied: '2025-09-22T16:45:00Z'
    }
  ]

  const mockDailyActivity: DailyActivity[] = [
    { date: '2025-09-18', questionsAnswered: 15, timeSpent: 35, accuracy: 80 },
    { date: '2025-09-19', questionsAnswered: 22, timeSpent: 48, accuracy: 86 },
    { date: '2025-09-20', questionsAnswered: 18, timeSpent: 42, accuracy: 83 },
    { date: '2025-09-21', questionsAnswered: 25, timeSpent: 55, accuracy: 88 },
    { date: '2025-09-22', questionsAnswered: 20, timeSpent: 38, accuracy: 85 },
    { date: '2025-09-23', questionsAnswered: 28, timeSpent: 62, accuracy: 89 },
    { date: '2025-09-24', questionsAnswered: 12, timeSpent: 25, accuracy: 92 }
  ]

  const mockAchievements: Achievement[] = [
    {
      id: 'first-correct',
      title: '初出茅庐',
      description: '答对第一道题目',
      icon: '🎯',
      unlockedAt: '2025-09-15T09:00:00Z',
      category: '基础成就'
    },
    {
      id: 'streak-7',
      title: '七日连胜',
      description: '连续7天学习',
      icon: '🔥',
      unlockedAt: '2025-09-21T18:30:00Z',
      category: '坚持成就'
    },
    {
      id: 'accuracy-90',
      title: '神射手',
      description: '单次练习正确率达到90%',
      icon: '🏹',
      unlockedAt: '2025-09-23T14:20:00Z',
      category: '精准成就'
    }
  ]

  useEffect(() => {
    loadAnalytics()
  }, [selectedPeriod])

  const loadAnalytics = async () => {
    try {
      setIsLoading(true)

      // 使用模拟数据
      setStats(mockStats)
      setTopicProgress(mockTopicProgress)
      setDailyActivity(mockDailyActivity)
      setAchievements(mockAchievements)
    } catch (err) {
      console.error('加载分析数据错误:', err)
      setError('加载分析数据时发生错误')
    } finally {
      setIsLoading(false)
    }
  }

  const loadStats = async () => {
    // TODO: 实现真实数据库查询
    setStats(mockStats)
  }

  const loadTopicProgress = async () => {
    // TODO: 实现真实数据库查询
    setTopicProgress(mockTopicProgress)
  }

  const loadDailyActivity = async () => {
    // TODO: 实现真实数据库查询
    setDailyActivity(mockDailyActivity)
  }

  const loadAchievements = async () => {
    // TODO: 实现真实数据库查询
    setAchievements(mockAchievements)
  }

  const formatTime = (minutes: number) => {
    const hours = Math.floor(minutes / 60)
    const mins = minutes % 60
    return hours > 0 ? `${hours}小时${mins}分钟` : `${mins}分钟`
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    })
  }

  const getDifficultyColor = (difficulty: number) => {
    const colors = {
      1: 'bg-green-100 text-green-800',
      2: 'bg-blue-100 text-blue-800',
      3: 'bg-yellow-100 text-yellow-800',
      4: 'bg-orange-100 text-orange-800',
      5: 'bg-red-100 text-red-800'
    }
    return colors[difficulty as keyof typeof colors] || 'bg-gray-100 text-gray-800'
  }

  const getAccuracyColor = (accuracy: number) => {
    if (accuracy >= 90) return 'text-green-600'
    if (accuracy >= 80) return 'text-blue-600'
    if (accuracy >= 70) return 'text-yellow-600'
    return 'text-red-600'
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载学习分析中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8 text-center"
        >
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            学习分析
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            深入了解您的学习进度和表现
          </p>
        </motion.div>

        {/* 错误提示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 rounded-lg bg-red-100 border border-red-300 text-red-700"
          >
            {error}
          </motion.div>
        )}

        {/* 时间段选择 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          className="mb-6"
        >
          <Card glassmorphism className="backdrop-blur-xl">
            <CardContent className="p-4">
              <div className="flex items-center justify-center gap-4">
                {[
                  { key: 'week', label: '最近一周' },
                  { key: 'month', label: '最近一月' },
                  { key: 'year', label: '最近一年' }
                ].map(period => (
                  <button
                    key={period.key}
                    onClick={() => setSelectedPeriod(period.key as any)}
                    className={`px-4 py-2 rounded-lg transition-all duration-200 ${
                      selectedPeriod === period.key
                        ? 'bg-blue-500 text-white'
                        : 'bg-white/50 text-gray-700 hover:bg-white/70'
                    }`}
                  >
                    {period.label}
                  </button>
                ))}
              </div>
            </CardContent>
          </Card>
        </motion.div>

        {/* 总体统计 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="grid grid-cols-2 md:grid-cols-4 gap-6 mb-8"
        >
          {stats && [
            {
              title: '学习时长',
              value: formatTime(stats.totalStudyTime),
              icon: Clock,
              color: 'text-blue-600'
            },
            {
              title: '答题总数',
              value: stats.questionsAnswered.toString(),
              icon: Target,
              color: 'text-green-600'
            },
            {
              title: '正确率',
              value: `${stats.accuracy.toFixed(1)}%`,
              icon: Award,
              color: getAccuracyColor(stats.accuracy)
            },
            {
              title: '连续天数',
              value: `${stats.streak}天`,
              icon: Zap,
              color: 'text-orange-600'
            }
          ].map((stat, index) => (
            <Card key={stat.title} glassmorphism className="backdrop-blur-xl">
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 mb-1">{stat.title}</p>
                    <p className={`text-2xl font-bold ${stat.color}`}>{stat.value}</p>
                  </div>
                  <stat.icon className={`w-8 h-8 ${stat.color}`} />
                </div>
              </CardContent>
            </Card>
          ))}
        </motion.div>

        <div className="grid lg:grid-cols-2 gap-6">
          {/* 知识点进度 */}
          <motion.div
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.3 }}
          >
            <Card glassmorphism className="backdrop-blur-xl">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <BookOpen className="w-5 h-5" />
                  知识点进度
                </CardTitle>
                <CardDescription>
                  各知识点的学习情况和掌握程度
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {topicProgress.map(topic => (
                    <div key={topic.topicId} className="p-4 rounded-lg bg-white/50">
                      <div className="flex items-center justify-between mb-2">
                        <div>
                          <h4 className="font-medium text-gray-800">{topic.topicName}</h4>
                          <p className="text-sm text-gray-600">{topic.category}</p>
                        </div>
                        <span className={`px-2 py-1 rounded-full text-xs font-medium ${getDifficultyColor(topic.difficulty)}`}>
                          难度{topic.difficulty}
                        </span>
                      </div>
                      <div className="grid grid-cols-3 gap-4 text-sm">
                        <div>
                          <span className="text-gray-600">答题数：</span>
                          <span className="font-medium">{topic.questionsAnswered}</span>
                        </div>
                        <div>
                          <span className="text-gray-600">正确率：</span>
                          <span className={`font-medium ${getAccuracyColor(topic.accuracy)}`}>
                            {topic.accuracy.toFixed(1)}%
                          </span>
                        </div>
                        <div>
                          <span className="text-gray-600">用时：</span>
                          <span className="font-medium">{formatTime(topic.timeSpent)}</span>
                        </div>
                      </div>
                      <div className="mt-2">
                        <div className="w-full bg-gray-200 rounded-full h-2">
                          <div
                            className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                            style={{ width: `${topic.accuracy}%` }}
                          ></div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </motion.div>

          {/* 每日活动 */}
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.4 }}
          >
            <Card glassmorphism className="backdrop-blur-xl">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <BarChart3 className="w-5 h-5" />
                  每日活动
                </CardTitle>
                <CardDescription>
                  最近一周的学习活动统计
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {dailyActivity.map(day => (
                    <div key={day.date} className="flex items-center justify-between p-3 rounded-lg bg-white/50">
                      <div className="flex items-center gap-3">
                        <div className="text-sm font-medium text-gray-700">
                          {formatDate(day.date)}
                        </div>
                        <div className="text-xs text-gray-500">
                          {formatTime(day.timeSpent)}
                        </div>
                      </div>
                      <div className="flex items-center gap-4">
                        <div className="text-sm">
                          <span className="text-gray-600">题数：</span>
                          <span className="font-medium">{day.questionsAnswered}</span>
                        </div>
                        <div className="text-sm">
                          <span className="text-gray-600">正确率：</span>
                          <span className={`font-medium ${getAccuracyColor(day.accuracy)}`}>
                            {day.accuracy}%
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </motion.div>
        </div>

        {/* 成就系统 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5 }}
          className="mt-8"
        >
          <Card glassmorphism className="backdrop-blur-xl">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Award className="w-5 h-5" />
                我的成就
              </CardTitle>
              <CardDescription>
                您已解锁的学习成就
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {achievements.map(achievement => (
                  <div key={achievement.id} className="p-4 rounded-lg bg-white/50 text-center">
                    <div className="text-3xl mb-2">{achievement.icon}</div>
                    <h4 className="font-medium text-gray-800 mb-1">{achievement.title}</h4>
                    <p className="text-sm text-gray-600 mb-2">{achievement.description}</p>
                    <p className="text-xs text-gray-500">
                      {new Date(achievement.unlockedAt).toLocaleDateString('zh-CN')} 解锁
                    </p>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </motion.div>
      </div>
    </div>
  )
}
